// 修复后的 src/components/SubscriptionCode/SubscriptionCode.tsx
import React, {useState} from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  ActivityIndicator,
} from 'react-native';
import {observer} from 'mobx-react';
import {useTheme} from '../../hooks';
import {L10nContext} from '../../utils';
import {uiStore} from '../../store/UIStore';
import {text} from '../../../__mocks__/external/@nozbe/watermelondb';

interface SubscriptionCodeProps {
  onCodeVerified: (code: string) => void;
}

export const SubscriptionCode: React.FC<SubscriptionCodeProps> = observer(
  ({onCodeVerified}) => {
    const [subscriptionCode, setSubscriptionCode] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const theme = useTheme();
    const l10n = React.useContext(L10nContext);
    const styles = createStyles(theme);

    const handleVerifyCode = async () => {
      if (!subscriptionCode.trim()) {
        Alert.alert('错误', '请输入订阅码');
        return;
      }

      setIsLoading(true);
      try {
        const isValid = await validateSubscriptionCode(subscriptionCode);

        if (isValid) {
          const expiry = formatCode(subscriptionCode); //输入为秒级时间戳
          const expiryDate = new Date(expiry * 1000); //毫秒
          const remainingDays = Math.ceil(
            (formatCode(subscriptionCode) - Math.floor(Date.now() / 1000)) /
              (24 * 60 * 60),
          );

          Alert.alert(
            '验证成功',
            `到期时间：${expiryDate.toLocaleDateString()}\n剩余天数：${remainingDays}天`,
            [
              {
                text: '确定',
                onPress: () => {
                  // 保存订阅信息
                  uiStore.setSubscription(
                    String(formatCode(subscriptionCode)),
                    expiry,
                  );
                  onCodeVerified(String(formatCode(subscriptionCode)));
                },
              },
            ],
          );
        } else {
          Alert.alert('错误', '订阅码无效或已过期', [
            {
              text: '返回',
              onPress: () => {},
            },
          ]);
        }
      } catch (error) {
        Alert.alert('错误', '验证过程中发生错误', [
          {
            text: '返回',
            onPress: () => {},
          },
        ]);
      } finally {
        setIsLoading(false);
      }
    };

    const formatCode = (code: string) => {
      console.log(code, 'code');

      if (!code) {
        return -1;
      }
      const timestamp = code
        ?.slice(2)
        ?.slice(0, -2)
        ?.split('')
        ?.reverse()
        ?.filter(item => item >= 0 && item <= 9)
        ?.join('');
      console.log(timestamp, 'codetimestamp');
      return Number(timestamp);
    };

    // 订阅码验证函数
    const validateSubscriptionCode = async (code: string): Promise<boolean> => {
      try {
        // 1. 检查是否为有效的时间戳格式
        const timestamp = formatCode(code);
        if (isNaN(timestamp) || timestamp <= 0) {
          console.log('000001');

          return false;
        }

        // 2. 检查是否为未来时间戳
        const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
        if (timestamp <= currentTime) {
          console.log('000002');
          return false;
        }

        // 3. 检查时间戳是否合理（比如不超过10年）
        const maxFutureTime = currentTime + 1 * 365 * 24 * 60 * 60; // 1年后
        if (timestamp > maxFutureTime) {
          console.log('000003');
          return false;
        }
        console.log('000004');
        return true;
      } catch (error) {
        console.error('订阅码验证错误:', error);
        return false;
      }
    };

    return (
      <View style={styles.container}>
        <View style={styles.content}>
          <View style={styles.logoContainer}>
            <Text style={styles.logo}>🔐</Text>
          </View>

          <Text style={styles.title}>订阅验证</Text>
          <Text style={styles.subtitle}>请输入您的订阅码以继续使用蕴明AI</Text>

          <View style={styles.inputContainer}>
            <TextInput
              style={styles.input}
              value={subscriptionCode}
              onChangeText={setSubscriptionCode}
              placeholder="输入订阅码"
              placeholderTextColor={theme.colors.onSurfaceVariant}
              autoCapitalize="characters"
              autoCorrect={false}
              maxLength={20}
            />
          </View>

          <TouchableOpacity
            style={[
              styles.button,
              (!subscriptionCode.trim() || isLoading) && styles.buttonDisabled,
            ]}
            onPress={handleVerifyCode}
            disabled={!subscriptionCode.trim() || isLoading}>
            {isLoading ? (
              <ActivityIndicator color={theme.colors.onPrimary} />
            ) : (
              <Text style={styles.buttonText}>验证</Text>
            )}
          </TouchableOpacity>

          {/* <View style={styles.helpContainer}>
            <Text style={styles.helpTitle}>如何获取订阅码？</Text>
            <Text style={styles.helpText}>
              • 联系客服购买订阅服务{'\n'}• 在官网注册获取试用码{'\n'}•
              查看购买确认邮件
            </Text>
          </View> */}
        </View>
      </View>
    );
  },
);

const createStyles = (theme: any) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: theme.colors.background,
      justifyContent: 'center',
      alignItems: 'center',
      padding: 20,
    },
    content: {
      width: '100%',
      maxWidth: 400,
      alignItems: 'center',
    },
    logoContainer: {
      marginBottom: 20,
    },
    logo: {
      fontSize: 60,
    },
    title: {
      fontSize: 28,
      fontWeight: 'bold',
      color: theme.colors.onBackground,
      marginBottom: 10,
      textAlign: 'center',
    },
    subtitle: {
      fontSize: 16,
      color: theme.colors.onSurfaceVariant,
      textAlign: 'center',
      marginBottom: 30,
      lineHeight: 24,
    },
    inputContainer: {
      width: '100%',
      marginBottom: 20,
    },
    input: {
      width: '100%',
      height: 56,
      borderWidth: 2,
      borderColor: theme.colors.outline,
      borderRadius: 12,
      paddingHorizontal: 16,
      fontSize: 18,
      color: theme.colors.onBackground,
      backgroundColor: theme.colors.surface,
      textAlign: 'center',
      letterSpacing: 2,
      fontWeight: '600',
    },
    button: {
      width: '100%',
      height: 56,
      backgroundColor: theme.colors.primary,
      borderRadius: 12,
      justifyContent: 'center',
      alignItems: 'center',
      marginBottom: 30,
      elevation: 2,
      shadowColor: theme.colors.primary,
      shadowOffset: {width: 0, height: 2},
      shadowOpacity: 0.3,
      shadowRadius: 4,
    },
    buttonDisabled: {
      backgroundColor: theme.colors.surfaceVariant,
      elevation: 0,
      shadowOpacity: 0,
    },
    buttonText: {
      color: theme.colors.onPrimary,
      fontSize: 18,
      fontWeight: '600',
    },
    helpContainer: {
      width: '100%',
      backgroundColor: theme.colors.surfaceVariant,
      borderRadius: 12,
      padding: 16,

      marginBottom: 20,
    },
    helpTitle: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.colors.onSurfaceVariant,
      marginBottom: 8,
    },
    helpText: {
      fontSize: 14,
      color: theme.colors.onSurfaceVariant,
      lineHeight: 20,
    },
    contactButton: {
      paddingVertical: 8,
      paddingHorizontal: 16,
    },
    contactText: {
      fontSize: 16,
      color: theme.colors.primary,
      fontWeight: '500',
    },
  });
